// todo 学生的接口
var express = require("express");
var router = express.Router();
const Students = require("../models/students");

const jwt = require("jsonwebtoken");
let secret = "I_LOVE_JING";

// todo 查询接口
router.get("/list", function (req, res, next) {
  // console.log(req.query);

  try {
    const { name, pageSize, currentPage, token } = req.query;

    let payload = jwt.verify(token, secret);
    console.log("payload", payload);

    // todo 5. 查询
    // Students.find(req.query, (err, doc) => {
    //   if (err) throw err;
    //   res.json({
    //     status: 0,
    //     list: doc,
    //   });
    // });

    Students.count(name ? { name } : {}, (err, count) => {
      if (err) throw err;
      Students.find(name ? { name } : {})
        .skip((+currentPage - 1) * +pageSize)
        .limit(+pageSize)
        .exec((err, doc) => {
          if (err) throw err;
          res.json({
            status: 0,
            count: count,
            list: doc,
          });
        });
    });
  } catch (err) {
    res.json({
      status: 1006,
      msg: "token错误",
    });
  }
});

// todo 删除接口
router.post("/del", (req, res, next) => {
  const { id } = req.body;

  if (id) {
    // todo 删除用模型的remove方法
    Students.remove({ _id: id }, (err) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: "删除成功",
      });
    });
  } else {
    res.json({
      status: 1001,
      msg: "参数错误",
    });
  }
});

// todo 添加接口
router.post("/add", (req, res, next) => {
  const { name, age, sex, num, address } = req.body;
  if (!name || !age || !sex || !num || !address) {
    res.json({
      status: 1001,
      msg: "参数错误",
    });
  } else {
    // todo 要存到数据库里面去了
    // todo 先通过模型得到一个实例，存的是实例
    const student = new Students({
      name,
      age: +age,
      sex: +sex,
      num: +num,
      address,
    });
    student.save((err) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: "新增成功",
      });
    });
  }
});

// todo 编辑
// router.post("/edit", (req, res, next) => {
//   Students.updateOne()
// })

module.exports = router;
